package com.sddongyun.filter;

import com.alibaba.fastjson.JSONObject;
import com.sddongyun.common.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author lxt
 */

public class HisServletFilter implements Filter {
    @Autowired
    JdbcTemplate jdbcTemplate;
    private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(HisServletFilter.class);
    private static final String DOWMLOAD_FILE = "/base/downloadFile";

    private static final String URI = "uri";

//    @Autowired
//    RedisService redisService;

    /**
     * 超时时间
     */
//    @Value("${authorization.timeout}")
    long timeout;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("HisServletFilter----"+((HttpServletRequest) request).getRequestURI());
        ServletRequest requestWrapper = null;
//        log.info("当前过滤器线程名称为{}",Thread.currentThread().getName());
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
        Enumeration<String> names = request.getParameterNames();
        JSONObject endJson = new JSONObject();
        endJson.put(URI, ((HttpServletRequest) request).getRequestURI());
        if (names.hasMoreElements()) {
            String hisMethod = request.getParameter("soap_method");
            String parameter = URLDecoder.decode(request.getParameter("input"), "utf-8");
            Matcher matcher = Pattern.compile("<TradeCode>.*?</TradeCode>").matcher(parameter);
            String reqCode = "";
            if (matcher.find()) {
                reqCode = matcher.group(0).toString();
            }
            endJson.put("reqDate", formatDate(new Date()));
            endJson.put("reqCode", reqCode);
            endJson.put("hisMehtod", hisMethod);
            endJson.put("parameter", parameter);
            chain.doFilter(request, responseWrapper);
        }
        //获取返回值
        byte[] content = responseWrapper.getContent();
        //判断是否有值
        if (content.length > 0) {
            String str = new String(content, "UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
            Matcher matcher = Pattern.compile("<Response>.*?</Response>").matcher(str);
            if (matcher.find()) {
                str = matcher.group(0).toString();
            }

            endJson.put("resStr", str);
            endJson.put("resDate", formatDate(new Date()));
        } else {
            endJson.put("resStr", String.valueOf(((HttpServletResponse) response).getStatus()));
            endJson.put("resDate", formatDate(new Date()));

        }
        jdbcTemplate.update(
                "insert into hisserverlog(serverip,url,reqdate,hismethod,reqcode,reqparams,resstr,resdate) VALUES (?,?,?,?,?,?,?,?)",
                "192.168.96.118",
                endJson.get(URI).toString(),
                endJson.get("reqDate").toString(),
                endJson.get("hisMehtod").toString(),
                endJson.get("reqCode").toString(),
                endJson.get("parameter").toString(),
                endJson.get("resStr").toString(),
                endJson.get("resDate").toString()
        );

    }

    public String formatDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    @Override
    public void destroy() {

    }
}